// pages/demand-list/demand-list.ts
import { getPublishList } from '../../api/publish';
import {PAGES, goToPage, PAGE_LOGIN} from '../../config/pages';
import { getDemandCategoryNames } from '../../config/product-categories';
import { formatDate } from '../../utils/time';
import { formatSpecification } from '../../utils/util';
import {checkLogin} from "../../libs/login";
import util from '../../utils/util';

Page({
  data: {
    demands: [] as any[],
    loading: false,
    page: 1,
    limit: 20,
    hasMore: true,
    // 筛选条件
    selectedProvince: '',
    selectedCity: '',
    selectedDistrict: '',
    selectedCategory: '', // all, material, processing
    filterActive: false,
    // 搜索关键词
    keyword: '',
    // 城市筛选弹窗
    showCityFilter: false,
    cityFilterValue: null as any,
    // 初始化完成标志
    initialized: false,
  },

  async onLoad() {
    await this.checkLoginStatus();
  },

  onShow() {
    // 更新TabBar选中状态
    if (typeof this.getTabBar === 'function' && this.getTabBar()) {
      this.getTabBar().setData({
        selected: 1  // 求购是第2个，索引为1
      });
    }

    // 只有在初始化完成后才加载数据
    if (this.data.initialized) {
      this.loadDemands();
    }
  },

  // 检查登录状态
  async checkLoginStatus() {
    // if (!checkLogin()) {
    //   // 未登录，跳转到登录页面
    //   goToPage(PAGE_LOGIN, {}, 'reLaunch');
    //   return;
    // }
    
    // 登录检查完成，设置初始化标志并加载数据
    this.setData({ initialized: true });
    this.loadDemands(true);
  },

  // 加载求购列表
  async loadDemands(refresh: boolean = false) {
    if (this.data.loading) return;
    
    if (refresh) {
      this.setData({
        page: 1,
        demands: [],
        hasMore: true
      });
    }

    this.setData({ loading: true });

    try {
      const params: any = {
        type: 'demand',
        page: this.data.page,
        limit: this.data.limit
      };

      // 添加筛选条件
      if (this.data.selectedProvince) {
        params.province = this.data.selectedProvince;
      }
      if (this.data.selectedCity) {
        params.city = this.data.selectedCity;
      }
      if (this.data.selectedDistrict) {
        params.district = this.data.selectedDistrict;
      }
      if (this.data.selectedCategory && this.data.selectedCategory !== 'all') {
        params.category = this.data.selectedCategory; // 使用category字段进行筛选
      }
      // 添加搜索关键词
      if (this.data.keyword) {
        params.keyword = this.data.keyword;
      }

      const res = await getPublishList(params);
      
      if (res.status === 200 && res.data) {
        // 格式化日期和规格
        const formattedList = res.data.list.map((item: any) => ({
          ...item,
          spec: formatSpecification(item.spec || ''),
          formatted_date: formatDate(item.add_time || item.create_time)
        }));
        
        const newDemands = refresh ? formattedList : [...this.data.demands, ...formattedList];
        
        this.setData({
          demands: newDemands,
          hasMore: newDemands.length < res.data.count,
          page: this.data.page + 1
        });
      }
    } catch (error) {
      console.error('加载求购列表失败:', error);
      wx.showToast({
        title: '加载失败',
        icon: 'none'
      });
    } finally {
      this.setData({ loading: false });
    }
  },

  // 下拉刷新
  onPullDownRefresh() {
    this.loadDemands(true);
    wx.stopPullDownRefresh();
  },

  // 上拉加载更多
  onReachBottom() {
    if (this.data.hasMore && !this.data.loading) {
      this.loadDemands();
    }
  },

  // 筛选全国
  filterNational() {
    this.setData({
      selectedProvince: '',
      selectedCity: '',
      selectedDistrict: '',
      filterActive: false
    });
    this.loadDemands(true);
  },

  // 显示城市选择弹窗
  showCityModal() {
    this.setData({
      showCityFilter: true,
      cityFilterValue: {
        province: this.data.selectedProvince,
        city: this.data.selectedCity,
        district: this.data.selectedDistrict
      }
    });
  },

  // 城市筛选确认
  onCityFilterConfirm(e: any) {
    const { address } = e.detail;
    console.log('选择的城市:', address);
    
    this.setData({
      selectedProvince: address.province || '',
      selectedCity: address.city || '',
      selectedDistrict: address.district || '',
      filterActive: true,
      showCityFilter: false
    });
    
    this.loadDemands(true);
  },

  // 城市筛选取消
  onCityFilterCancel() {
    this.setData({
      showCityFilter: false
    });
  },

  // 清除城市筛选
  onCityFilterClear() {
    this.setData({
      selectedProvince: '',
      selectedCity: '',
      selectedDistrict: '',
      filterActive: false,
      showCityFilter: false
    });
    this.loadDemands(true);
  },

  // 选择全国
  onCityFilterNational() {
    this.setData({
      selectedProvince: '',
      selectedCity: '',
      selectedDistrict: '',
      filterActive: false,
      showCityFilter: false
    });
    this.loadDemands(true);
  },

  // 显示分类筛选弹窗
  showCategoryModal() {
    const demandCategories = getDemandCategoryNames();
    const categories = ['全部分类', ...demandCategories];
    wx.showActionSheet({
      itemList: categories,
      success: (res) => {
        const categoryValues = ['all', ...demandCategories];
        this.setData({
          selectedCategory: categoryValues[res.tapIndex]
        });
        this.loadDemands(true);
      }
    });
  },

  // 跳转到求购详情
  goToDetail(e: any) {
    const id = e.currentTarget.dataset.id;
    goToPage(PAGES.DEMAND_DETAIL, { id });
  },

  // 搜索
  onSearch(e: any) {
    const keyword = e.detail.value;
    console.log('搜索关键词:', keyword);
    this.setData({
      keyword: keyword.trim()
    });
    this.loadDemands(true);
  },

  // 清除搜索
  clearSearch() {
    this.setData({
      keyword: ''
    });
    this.loadDemands(true);
  },

  // 轮播图链接跳转事件
  onBannerLinkTap(e: any) {
    const { linkUrl } = e.detail;
    console.log('轮播图链接跳转:', linkUrl);
    util.navigateToAdLink(linkUrl);
  }

});
